from django import views
from django.shortcuts import render, HttpResponse, redirect
from rbac.models import UserInfo
from rbac.permissions.p_initial import permission_initial
from app_main.kit.encryption import use_md5


class Login(views.View):
    def get(self, request):
        s_key = request.session.session_key
        if not request.session.exists(s_key):
            return render(request, 'app_main/login.html')
        else:
            return render(request, 'stark/index.html')

    def post(self, request):
        user = request.POST.get('user')
        pwd = use_md5(request.POST.get('password', ''))
        current_user = UserInfo.objects.filter(name=user, password=pwd).first()
        if current_user:
            request.session['user_info'] = {'id': current_user.id, 'nickname': current_user.nickname}
            return permission_initial(current_user, request)
        else:
            return render(request, 'app_main/login.html', {'msg': '用户名或密码错误'})


class Logout(views.View):
    def get(self, request):
        s_key = request.session.session_key
        if request.session.exists(s_key):
            request.session.delete()
            return redirect('/')
        else:
            return HttpResponse('请先登录')
